package com.itaming.lycheeframework.mybatisflex.autofill;

import com.itaming.lycheeframework.mybatisflex.base.BaseEntity;
import com.mybatisflex.annotation.UpdateListener;
import lombok.RequiredArgsConstructor;

import java.time.LocalDateTime;

/**
 * BaseEntity更新监听器
 *
 * @author A.Ming
 */
@RequiredArgsConstructor
public class BaseEntityUpdateListener implements UpdateListener {

    /**
     * 自动填充提供者
     */
    private final AutoFillProvider autoFillProvider;

    @Override
    public void onUpdate(Object o) {
        // 转换实体
        BaseEntity entity = (BaseEntity) o;

        // 获取填充值
        Long currentUserId = autoFillProvider.getCurrentUserId();
        LocalDateTime now = LocalDateTime.now();

        // 设置填充值
        if (entity.getUpdateUser() == null) {
            entity.setUpdateUser(currentUserId);
        }
        if (entity.getUpdateTime() == null) {
            entity.setUpdateTime(now);
        }
    }

}
